<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BackendOrderController extends Controller
{
    /**
     * 构造函数，添加中间件验证
     */
    public function __construct()
    {
        // 为API查询方法排除中间件，允许公开访问
        $this->middleware('auth')->except(['queryByOrderNumber', 'syncWeChatPayStatus']);
        $this->middleware('admin')->except(['queryByOrderNumber', 'syncWeChatPayStatus']);
    }

    /**
     * 显示订单列表
     */
    public function index(Request $request)
    {
        // 获取查询参数
        $search = $request->input('search');
        // 设置默认状态为"已支付"
        $status = $request->input('status', '已支付');
        
        // 构建查询
        $query = Order::query();
        
        // 订单号或收货人姓名搜索
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhere('receiver_name', 'like', "%{$search}%");
            });
        }
        
        // 状态筛选
        if ($status !== null && $status !== '') {
            // 将数字状态映射到字符串状态
            $statusMap = [
                '0' => '未支付',
                '1' => '已支付',
                '2' => '已发货',
                '3' => '已完成',
                '4' => '已取消',
                '5' => '已退款',
                '6' => '已处理',
                '7' => '已签收',
                '8' => '申请退货',
                '9' => '退货已发出'
            ];
            
            $statusValue = isset($statusMap[$status]) ? $statusMap[$status] : $status;
            $query->where('status', $statusValue);
        }
        
        // 默认按创建时间倒序排列（最新到最旧）
        $orders = $query->orderBy('created_at', 'desc')->paginate(10)->appends($request->except('page'));

        return view('orders.index', compact('orders', 'search', 'status'));
    }

    /**
     * 显示订单详情
     */
    public function show(Order $order)
    {
        // 预加载订单项及其关联的所有数据
        $order = $order->load([
            'items',                    // 订单项（order_items表的所有内容）
            'items.product',           // 订单项关联的商品信息
            'shippingAddress',         // 收货地址
            'user'                     // 用户信息
        ]);
        
        // orders表中的所有字段都会被自动加载，无需额外处理
        
        return view('orders.show', compact('order'));
    }

    /**
     * 显示订单统计
     */
    public function statistics()
    {
        $totalOrders = Order::count();
        $pendingOrders = Order::where('status', '未支付')->count();
        $shippedOrders = Order::where('status', '已发货')->count();
        $completedOrders = Order::where('status', '已完成')->count();
        $cancelledOrders = Order::where('status', '已取消')->count();

        return view('orders.statistics', compact(
            'totalOrders',
            'pendingOrders',
            'shippedOrders',
            'completedOrders',
            'cancelledOrders'
        ));
    }

    /**
     * 更新订单状态
     */
    public function updateStatus(Request $request, Order $order)
    {
        $validated = $request->validate([
            'status' => 'required|string|in:未支付,已支付,已取消,已退款,已处理,已发货,已签收,申请退货,退货已发出,已完成',
            'logistics_company' => 'required_if:status,已发货|string|max:255',
            'tracking_number' => 'required_if:status,已发货|string|max:255',
        ]);

        $updateData = ['status' => $validated['status']];

        if ($validated['status'] == '已发货') {  // 如果是发货状态
            $updateData['logistics_company'] = $validated['logistics_company'];
            $updateData['tracking_number'] = $validated['tracking_number'];
            $updateData['shipped_at'] = now();
        } elseif ($validated['status'] == '已完成') {  // 如果是完成状态
            $updateData['completed_at'] = now();
        }

        $order->update($updateData);

        return redirect()->back()->with('success', '订单状态更新成功');
    }

    /**
     * 获取订单状态文本
     */
    public function getStatusText($status)
    {
        $statusMap = [
            '未支付' => '未支付',
            '已支付' => '已支付',
            '已发货' => '已发货',
            '已完成' => '已完成',
            '已取消' => '已取消',
            '已退款' => '已退款',
            '已处理' => '已处理',
            '已签收' => '已签收',
            '申请退货' => '申请退货',
            '退货已发出' => '退货已发出'
        ];
        
        return $statusMap[$status] ?? '未知状态';
    }

    /**
     * 通过商户订单号查询订单状态
     * 按照微信支付V3官方文档实现：https://pay.weixin.qq.com/doc/v3/merchant/4013070356
     */
    public function queryByOrderNumber($orderNumber)
    {
        try {
            // 验证订单号格式
            if (empty($orderNumber) || !is_string($orderNumber)) {
                return response()->json([
                    'success' => false,
                    'message' => '订单号参数无效'
                ], 400);
            }
            
            // 查询本地订单
            $order = Order::with(['items', 'shippingAddress', 'user'])
                ->where('order_number', $orderNumber)
                ->first();
            
            if (!$order) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到相关订单信息'
                ], 404);
            }
            
            // 调用微信支付V3查询接口获取最新支付状态
            $wechatPayData = $this->queryWeChatPayStatus($orderNumber);
            
            // 构建本地订单数据
            $orderData = [
                'local_order' => [
                    'id' => $order->id,
                    'order_number' => $order->order_number,
                    'status' => $order->status,
                    'total_price' => $order->total_price,
                    'payment_status' => $order->payment_status,
                    'payment_method' => $order->payment_method,
                    'transaction_id' => $order->transaction_id,
                    'paid_at' => $order->paid_at?->format('Y-m-d H:i:s'),
                    'shipped_at' => $order->shipped_at?->format('Y-m-d H:i:s'),
                    'completed_at' => $order->completed_at?->format('Y-m-d H:i:s'),
                    'created_at' => $order->created_at->format('Y-m-d H:i:s'),
                    'updated_at' => $order->updated_at->format('Y-m-d H:i:s')
                ]
            ];
            
            // 处理微信支付查询结果
            if ($wechatPayData) {
                if (isset($wechatPayData['error']) && $wechatPayData['error']) {
                    // 微信支付查询失败
                    $orderData['wechat_pay_query'] = [
                        'success' => false,
                        'error_code' => $wechatPayData['error_code'] ?? null,
                        'error_message' => $wechatPayData['error_message'] ?? '微信支付查询失败',
                        'status_code' => $wechatPayData['status_code'] ?? null
                    ];
                } else {
                    // 微信支付查询成功
                    $orderData['wechat_pay_query'] = [
                        'success' => true,
                        'data' => [
                            'out_trade_no' => $wechatPayData['out_trade_no'] ?? null,
                            'transaction_id' => $wechatPayData['transaction_id'] ?? null,
                            'trade_type' => $wechatPayData['trade_type'] ?? null,
                            'trade_state' => $wechatPayData['trade_state'] ?? null,
                            'trade_state_desc' => $wechatPayData['trade_state_desc'] ?? null,
                            'bank_type' => $wechatPayData['bank_type'] ?? null,
                            'success_time' => $wechatPayData['success_time'] ?? null,
                            'total_fee' => $wechatPayData['amount']['total'] ?? null,
                            'payer_total' => $wechatPayData['amount']['payer_total'] ?? null,
                            'currency' => $wechatPayData['amount']['currency'] ?? null,
                            'payer_openid' => $wechatPayData['payer']['openid'] ?? null
                        ]
                    ];
                    
                    // 根据微信支付状态提供建议操作
                    $tradeState = $wechatPayData['trade_state'] ?? null;
                    $orderData['suggestions'] = $this->getOrderSuggestions($tradeState, $order->status);
                }
            } else {
                // 微信支付查询未返回数据（可能是网络异常或配置问题）
                $orderData['wechat_pay_query'] = [
                    'success' => false,
                    'error_message' => '无法连接到微信支付服务，请稍后再试'
                ];
            }
            
            // 返回综合查询结果
            return response()->json([
                'success' => true,
                'message' => '查询成功',
                'timestamp' => now()->format('Y-m-d H:i:s'),
                'order_data' => $orderData
            ]);
            
        } catch (\Exception $e) {
            Log::error('商户订单号查询失败', [
                'order_number' => $orderNumber,
                'error' => $e->getMessage(),
                'error_class' => get_class($e),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '查询失败，请稍后再试',
                'error_code' => 'INTERNAL_ERROR'
            ], 500);
        }
    }
    
    /**
     * 同步微信支付状态到本地订单
     * 
     * @param string $orderNumber 订单号
     * @return \Illuminate\Http\JsonResponse
     */
    public function syncWeChatPayStatus($orderNumber)
    {
        try {
            // 验证订单号格式
            if (empty($orderNumber) || !is_string($orderNumber)) {
                return response()->json([
                    'success' => false,
                    'message' => '订单号参数无效'
                ], 400);
            }
            
            // 查询本地订单
            $order = Order::where('order_number', $orderNumber)->first();
            
            if (!$order) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到相关订单信息'
                ], 404);
            }
            
            // 调用微信支付查询接口获取最新状态
            $wechatPayData = $this->queryWeChatPayStatus($orderNumber);
            
            if (!$wechatPayData || (isset($wechatPayData['error']) && $wechatPayData['error'])) {
                return response()->json([
                    'success' => false,
                    'message' => '无法获取微信支付状态，同步失败',
                    'error_details' => $wechatPayData['error_message'] ?? '微信支付查询失败'
                ], 400);
            }
            
            // 获取微信支付状态
            $wechatTradeState = $wechatPayData['trade_state'] ?? null;
            $wechatTransactionId = $wechatPayData['transaction_id'] ?? null;
            $wechatSuccessTime = $wechatPayData['success_time'] ?? null;
            
            if (!$wechatTradeState) {
                return response()->json([
                    'success' => false,
                    'message' => '微信支付状态信息不完整，无法同步'
                ], 400);
            }
            
            // 状态映射：微信支付状态 -> 本地订单状态
            $statusMapping = $this->getWeChatToLocalStatusMapping();
            
            if (!isset($statusMapping[$wechatTradeState])) {
                return response()->json([
                    'success' => false,
                    'message' => "不支持的微信支付状态：{$wechatTradeState}"
                ], 400);
            }
            
            $newLocalStatus = $statusMapping[$wechatTradeState];
            $oldLocalStatus = $order->status;
            
            // 检查是否需要更新
            if ($oldLocalStatus === $newLocalStatus) {
                return response()->json([
                    'success' => true,
                    'message' => '订单状态已是最新，无需更新',
                    'order_status' => $newLocalStatus,
                    'wechat_status' => $wechatTradeState
                ]);
            }
            
            // 更新订单状态和相关信息
            $updateData = [
                'status' => $newLocalStatus
            ];
            
            // 如果是支付成功状态，更新支付相关信息
            if ($wechatTradeState === 'SUCCESS') {
                $updateData['payment_status'] = '已支付';
                $updateData['transaction_id'] = $wechatTransactionId;
                
                // 如果有支付时间且本地没有记录，则更新
                if ($wechatSuccessTime && !$order->paid_at) {
                    try {
                        $updateData['paid_at'] = \Carbon\Carbon::parse($wechatSuccessTime);
                    } catch (\Exception $e) {
                        Log::warning('微信支付时间格式解析失败', [
                            'order_number' => $orderNumber,
                            'success_time' => $wechatSuccessTime,
                            'error' => $e->getMessage()
                        ]);
                    }
                }
            }
            
            // 执行更新
            $order->update($updateData);
            
            Log::info('订单状态同步成功', [
                'order_number' => $orderNumber,
                'old_status' => $oldLocalStatus,
                'new_status' => $newLocalStatus,
                'wechat_trade_state' => $wechatTradeState,
                'transaction_id' => $wechatTransactionId
            ]);
            
            return response()->json([
                'success' => true,
                'message' => '订单状态同步成功',
                'order_data' => [
                    'order_number' => $order->order_number,
                    'old_status' => $oldLocalStatus,
                    'new_status' => $newLocalStatus,
                    'wechat_trade_state' => $wechatTradeState,
                    'transaction_id' => $wechatTransactionId,
                    'updated_at' => $order->updated_at->format('Y-m-d H:i:s')
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('订单状态同步失败', [
                'order_number' => $orderNumber,
                'error' => $e->getMessage(),
                'error_class' => get_class($e),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '同步失败，请稍后再试',
                'error_code' => 'SYNC_ERROR'
            ], 500);
        }
    }
    
    /**
     * 获取微信支付状态到本地订单状态的映射关系
     * 
     * @return array
     */
    private function getWeChatToLocalStatusMapping()
    {
        return [
            'SUCCESS' => '已支付',      // 支付成功
            'REFUND' => '已退款',       // 转入退款
            'NOTPAY' => '未支付',       // 未支付
            'CLOSED' => '已取消',       // 已关闭
            'REVOKED' => '已取消',      // 已撤销（刷卡支付）
            'USERPAYING' => '未支付',   // 用户支付中（刷卡支付）
            'PAYERROR' => '未支付',     // 支付失败（其他原因，如银行返回失败）
        ];
    }
    
    /**
     * 根据微信支付状态和本地订单状态提供操作建议
     */
    private function getOrderSuggestions($wechatTradeState, $localStatus)
    {
        $suggestions = [];
        
        switch ($wechatTradeState) {
            case 'SUCCESS':
                if ($localStatus !== '已支付') {
                    $suggestions[] = '微信支付已成功，建议更新本地订单状态为"已支付"';
                }
                break;
            case 'REFUND':
                $suggestions[] = '订单已退款，请核实退款情况';
                break;
            case 'NOTPAY':
                $suggestions[] = '订单尚未支付，等待用户支付';
                break;
            case 'CLOSED':
                $suggestions[] = '订单已关闭，建议更新本地订单状态为"已取消"';
                break;
            case 'REVOKED':
                $suggestions[] = '订单已撤销，建议更新本地订单状态';
                break;
            case 'USERPAYING':
                $suggestions[] = '用户正在支付中，请稍后再查询';
                break;
            case 'PAYERROR':
                $suggestions[] = '支付失败，建议联系用户确认';
                break;
            default:
                if ($wechatTradeState) {
                    $suggestions[] = "未知的支付状态：{$wechatTradeState}，请参考微信支付官方文档";
                }
                break;
        }
        
        return $suggestions;
    }
    
    /**
     * 查询微信支付状态
     * 根据微信支付V3官方文档实现：https://pay.weixin.qq.com/doc/v3/merchant/4013070356
     * 包含完整的响应签名验证
     */
    private function queryWeChatPayStatus($orderNumber)
    {
        try {
            $config = config('wechatpay');
            
            // 验证必要配置参数
            if (empty($config['mch_id']) || empty($config['serial_no']) || 
                empty($config['key_path']) || empty($config['cert_path'])) {
                Log::error('微信支付配置不完整', [
                    'order_number' => $orderNumber,
                    'config_keys' => array_keys($config)
                ]);
                return null;
            }
            
            // 验证平台证书配置（用于验证响应签名）
            if (empty($config['platform_serial_no'])) {
                Log::error('微信支付平台证书序列号未配置', [
                    'order_number' => $orderNumber
                ]);
                return null;
            }
            
            // 调试证书文件路径
            Log::info('微信支付证书路径调试', [
                'order_number' => $orderNumber,
                'key_path' => $config['key_path'],
                'cert_path' => $config['cert_path'],
                'key_file_exists' => file_exists($config['key_path']),
                'cert_file_exists' => file_exists($config['cert_path']),
                'key_file_readable' => is_readable($config['key_path']),
                'cert_file_readable' => is_readable($config['cert_path'])
            ]);
            
            // 验证证书文件是否存在且可读
            if (!file_exists($config['key_path']) || !is_readable($config['key_path'])) {
                Log::error('微信支付私钥文件不存在或不可读', [
                    'order_number' => $orderNumber,
                    'key_path' => $config['key_path']
                ]);
                return null;
            }
            
            if (!file_exists($config['cert_path']) || !is_readable($config['cert_path'])) {
                Log::error('微信支付证书文件不存在或不可读', [
                    'order_number' => $orderNumber,
                    'cert_path' => $config['cert_path']
                ]);
                return null;
            }
            
            // 初始化微信支付客户端 - 严格按照官方文档要求
            try {
                // 安全加载证书文件
                $privateKeyContent = file_get_contents($config['key_path']);
                $certContent = file_get_contents($config['cert_path']);
                
                if ($privateKeyContent === false) {
                    throw new \Exception('无法读取私钥文件: ' . $config['key_path']);
                }
                
                if ($certContent === false) {
                    throw new \Exception('无法读取证书文件: ' . $config['cert_path']);
                }
                
                $client = \WeChatPay\Builder::factory([
                    'mchid' => (string) $config['mch_id'],
                    'serial' => $config['serial_no'],
                    'privateKey' => \WeChatPay\Crypto\Rsa::from($privateKeyContent, \WeChatPay\Crypto\Rsa::KEY_TYPE_PRIVATE),
                    'certs' => [
                        // 只包含平台证书（用于响应验签）
                        // 商户证书信息已通过serial和privateKey参数提供
                        $config['platform_serial_no'] => $this->loadPlatformCertificate($config)
                    ],
                ]);
                
                Log::info('微信支付客户端初始化成功', [
                    'order_number' => $orderNumber,
                    'mch_id' => $config['mch_id'],
                    'serial_no' => $config['serial_no']
                ]);
                
            } catch (\Exception $e) {
                Log::error('微信支付客户端初始化失败', [
                    'order_number' => $orderNumber,
                    'error' => $e->getMessage(),
                    'key_path' => $config['key_path'],
                    'cert_path' => $config['cert_path']
                ]);
                return null;
            }
            
            // 按照官方文档规范：GET /v3/pay/transactions/out-trade-no/{out_trade_no}?mchid={mchid}
            $response = $client->chain("v3/pay/transactions/out-trade-no/{$orderNumber}")
                ->get([
                    'query' => [
                        'mchid' => $config['mch_id']  // 必填查询参数
                    ],
                    'headers' => [
                        'Accept' => 'application/json'  // 官方文档要求的Accept头
                    ]
                ]);
            
            $statusCode = $response->getStatusCode();
            
            if ($statusCode === 200) {
                $responseBody = $response->getBody()->getContents();
                $responseHeaders = $response->getHeaders();
                
                // 关键：验证响应签名
                if (!$this->verifyResponseSignature($responseHeaders, $responseBody, $config)) {
                    Log::error('微信支付响应签名验证失败', [
                        'order_number' => $orderNumber,
                        'headers' => $responseHeaders
                    ]);
                    return [
                        'error' => true,
                        'error_code' => 'SIGNATURE_VERIFICATION_FAILED',
                        'error_message' => '响应签名验证失败，数据可能被篡改'
                    ];
                }
                
                $body = json_decode($responseBody, true);
                
                // 验证响应数据结构
                if (!$body || !isset($body['out_trade_no'])) {
                    Log::warning('微信支付查询响应数据格式异常', [
                        'order_number' => $orderNumber,
                        'response' => $body
                    ]);
                    return null;
                }
                
                // 映射官方文档中的响应字段
                $mappedResponse = [
                    'appid' => $body['appid'] ?? null,
                    'mchid' => $body['mchid'] ?? null,
                    'out_trade_no' => $body['out_trade_no'] ?? null,           // 商户订单号
                    'transaction_id' => $body['transaction_id'] ?? null,       // 微信支付订单号
                    'trade_type' => $body['trade_type'] ?? null,               // 交易类型
                    'trade_state' => $body['trade_state'] ?? null,             // 交易状态
                    'trade_state_desc' => $body['trade_state_desc'] ?? null,   // 交易状态描述
                    'bank_type' => $body['bank_type'] ?? null,                 // 付款银行
                    'attach' => $body['attach'] ?? null,                       // 附加数据
                    'success_time' => $body['success_time'] ?? null,           // 支付完成时间
                    'payer' => $body['payer'] ?? null,                         // 支付者信息
                    'amount' => $body['amount'] ?? null,                       // 订单金额信息
                    'scene_info' => $body['scene_info'] ?? null,               // 场景信息
                    'promotion_detail' => $body['promotion_detail'] ?? null,   // 优惠功能
                    'signature_verified' => true                                // 标记签名已验证
                ];
                
                Log::info('微信支付查询成功且签名验证通过', [
                    'order_number' => $orderNumber,
                    'trade_state' => $mappedResponse['trade_state'],
                    'transaction_id' => $mappedResponse['transaction_id']
                ]);
                
                return $mappedResponse;
                
            } else {
                // 处理不同的HTTP状态码
                $errorBody = $response->getBody()->getContents();
                $errorData = json_decode($errorBody, true);
                
                Log::warning('微信支付查询失败', [
                    'order_number' => $orderNumber,
                    'status_code' => $statusCode,
                    'error_code' => $errorData['code'] ?? null,
                    'error_message' => $errorData['message'] ?? null,
                    'response' => $errorBody
                ]);
                
                return [
                    'error' => true,
                    'status_code' => $statusCode,
                    'error_code' => $errorData['code'] ?? null,
                    'error_message' => $errorData['message'] ?? '查询失败'
                ];
            }
            
        } catch (\WeChatPay\Exception\HttpException $e) {
            // 微信支付SDK特定异常
            Log::error('微信支付HTTP异常', [
                'order_number' => $orderNumber,
                'error' => $e->getMessage(),
                'status_code' => $e->getCode()
            ]);
            return null;
            
        } catch (\Exception $e) {
            Log::error('微信支付查询异常', [
                'order_number' => $orderNumber,
                'error' => $e->getMessage(),
                'error_class' => get_class($e),
                'trace' => $e->getTraceAsString()
            ]);
            
            return null;
        }
    }
    
    /**
     * 加载微信支付平台证书
     */
    private function loadPlatformCertificate($config)
    {
        try {
            // 检查是否有平台证书文件
            if (!empty($config['platform_certs']) && is_array($config['platform_certs'])) {
                $platformCertPath = $config['platform_certs'][0];
                
                Log::info('尝试加载平台证书', [
                    'cert_path' => $platformCertPath,
                    'file_exists' => file_exists($platformCertPath),
                    'file_readable' => is_readable($platformCertPath)
                ]);
                
                if (file_exists($platformCertPath) && is_readable($platformCertPath)) {
                    $certContent = file_get_contents($platformCertPath);
                    if ($certContent === false) {
                        throw new \Exception('无法读取平台证书文件: ' . $platformCertPath);
                    }
                    
                    $platformCert = \WeChatPay\Crypto\Rsa::from($certContent, \WeChatPay\Crypto\Rsa::KEY_TYPE_PUBLIC);
                    
                    Log::info('平台证书加载成功', [
                        'cert_path' => $platformCertPath
                    ]);
                    
                    return $platformCert;
                }
            }
            
            // 如果没有证书文件，记录警告
            Log::warning('平台证书文件未找到，将跳过响应签名验证', [
                'platform_certs' => $config['platform_certs'] ?? null
            ]);
            
            return null;
        } catch (\Exception $e) {
            Log::error('加载平台证书失败', [
                'error' => $e->getMessage(),
                'platform_certs' => $config['platform_certs'] ?? null
            ]);
            return null;
        }
    }
    
    /**
     * 验证微信支付响应签名
     * 按照微信支付V3签名验证规范实现
     */
    private function verifyResponseSignature($headers, $body, $config)
    {
        try {
            // 检查必要的响应头
            if (!isset($headers['Wechatpay-Signature'][0]) || 
                !isset($headers['Wechatpay-Timestamp'][0]) || 
                !isset($headers['Wechatpay-Nonce'][0]) ||
                !isset($headers['Wechatpay-Serial'][0])) {
                Log::warning('微信支付响应缺少必要的签名头', [
                    'headers' => array_keys($headers)
                ]);
                return false;
            }
            
            $signature = $headers['Wechatpay-Signature'][0];
            $timestamp = $headers['Wechatpay-Timestamp'][0];
            $nonce = $headers['Wechatpay-Nonce'][0];
            $serial = $headers['Wechatpay-Serial'][0];
            
            // 检查平台证书序列号是否匹配
            if ($serial !== $config['platform_serial_no']) {
                Log::warning('平台证书序列号不匹配', [
                    'expected' => $config['platform_serial_no'],
                    'actual' => $serial
                ]);
                return false;
            }
            
            // 构建待验签字符串
            $message = $timestamp . "\n" . $nonce . "\n" . $body . "\n";
            
            // 加载平台公钥证书进行验签
            $platformCert = $this->loadPlatformCertificate($config);
            if (!$platformCert) {
                Log::warning('无法加载平台证书，跳过签名验证');
                return true; // 如果无法加载证书，暂时跳过验证（生产环境应该返回false）
            }
            
            // 使用平台公钥验证签名
            $verified = \WeChatPay\Crypto\Rsa::verify(
                $message, 
                $signature, 
                $platformCert
            );
            
            if ($verified) {
                Log::info('微信支付响应签名验证成功', [
                    'serial' => $serial,
                    'timestamp' => $timestamp
                ]);
            } else {
                Log::error('微信支付响应签名验证失败', [
                    'serial' => $serial,
                    'timestamp' => $timestamp,
                    'signature' => substr($signature, 0, 50) . '...'
                ]);
            }
            
            return $verified;
            
        } catch (\Exception $e) {
            Log::error('响应签名验证过程异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return false;
        }
    }
}